package com.telnetnz.ticketdesk.action.user;

import org.apache.log4j.Logger;

import com.rockbb.common.simpleframe.config.SimpleConfig;
import com.rockbb.common.utilities.security.StringDigest;
import com.rockbb.common.utilities.text.StringUtils;
import com.telnetnz.ticketdesk.action.base.BasicSessionPageLogAction;
import com.telnetnz.ticketdesk.action.common.CommonUtils;
import com.telnetnz.ticketdesk.bean.User;
import com.telnetnz.ticketdesk.service.OperationLogService;
import com.telnetnz.ticketdesk.service.UserService;

public class UserEditAction extends BasicSessionPageLogAction
{
	private static Logger logger = Logger.getLogger(UserEditAction.class);

	public String doEdit()
	{
		EditUserBean bean = new EditUserBean();

		if (bean.getUser() == null)
		{
			return this.message_box(
					langRes.get("global.operation-fail"),
					langRes.get("user.user-not-exist", new String[]{bean.getRedirect()}),
					bean.getRedirect(),
					2);
		}

		if (bean.isSubmitted() && bean.validate())
		{
			UserService.updateUser(bean.getUser());

			OperationLogService.addLog(
					OperationLogService.OBJECT_TYPE_USER,
					bean.getUser().getId(),
					getSession().getSession_uuid(),
					getContext().getActionName(),
					null);

			return this.message_box(
					langRes.get("global.operation-success"), 
					langRes.get("user.profile-update-success-message", new String[]{bean.getRedirect()}),
					bean.getRedirect(),
					3
				);
		}

		if (bean.getUser() == null)
		{
			return this.message_box(
					langRes.get("global.error"), 
					langRes.get("user.user-not-exist")
				);
		}

		this.put_page_key("bean", bean);
		this.put_page_key("post_action", baseLink());

		// Language options
		this.put_page_key("language_options", CommonUtils.buildLanguageDropdown(SimpleConfig.getLanguages(), bean.getUser().getLanguage(), false));
		// Time zone options
		this.put_page_key("timezone_options", CommonUtils.buildTimezoneDropdown(langRes, bean.getUser().getTimezone()));

		return INPUT;
	}

	public class EditUserBean extends RequestBean
	{
		private User user;
		private String passwd;
		private String passwd_confirm;

		public User getUser() {
			return user;
		}

		@Override
		protected void loadRequest()
		{
			long id = getSession().getSession_uuid();
			user = UserService.getRawUser(id);
			if (user != null && this.isSubmitted())
			{
				passwd = get("passwd");
				passwd_confirm = get("passwd_confirm");

				user.setEmail(get("useremail"));
				user.setLanguage(getInt("language", 0, 0, getLanguages().size()-1));
				user.setTimezone(
						getFloat("timezone", UserService.USER_TZONE_ANONYMOUS, UserService.USER_TIMEZONE_KEYS));
			}
		}

		@Override
		protected boolean validate()
		{
			boolean flag = true;

			// Email
			if (!StringUtils.isEmailAddress(user.getEmail()))
			{
				flag = false;
				this.put_error_msg("useremail", langRes.get("user.email-invalid"));
			}
			else
			{
				User dummy = UserService.getByEmail(user.getEmail());
				if (dummy != null && dummy.getId() != user.getId())
				{
					flag = false;
					this.put_error_msg("useremail", langRes.get("user.email-already-exists"));
				}
			}

			// Password
			if (passwd.length() > 0)
			{
				if (!passwd.equals(passwd_confirm))
				{
					flag = false;
					this.put_error_msg("passwd", langRes.get("user.password-not-match"));
					this.put_error_msg("passwd_confirm", langRes.get("user.password-not-match"));
				}
				else
				{
					user.setPassword(StringDigest.hash(passwd));
				}
			}

			return flag;
		}
	}
}
